package com.sjk.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class EncryptAlgorithm {

    public static final String FIRST_SALT = "NLTgFxkSMG";

    public static final String SECOND_SALT = "KNqDIxp7zc";

    //需要加密调用encrypt方法，传入需要加密的字符串即可
    public static String encrypt(String input) {
        String firstAns = md5encrypt(input, FIRST_SALT);
        return md5encrypt(firstAns, SECOND_SALT);
    }

    private static String md5encrypt(String toBeEncryptedString, String salt) {
        String concertString = toBeEncryptedString + salt;
//        System.out.println(concertString);

        //创建MessageDigest对象
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("md5");
        } catch (NoSuchAlgorithmException e) {
            return "No Such Algorithm.";
        }

        //更新报文摘要对象，传入需要计算的字符串
        md5.update(concertString.getBytes());

        //计算摘要，计算的结果通过字节类型的数组返回
        byte[] md5Bytes = md5.digest();

        //结果转化成字符串
        StringBuffer result = new StringBuffer();
        for (byte md5Byte : md5Bytes) {
            int val = ((int) md5Byte) & 0xff;
            if (val < 16) {
                result.append("0");
            }
            result.append(Integer.toHexString(val));
        }
        return result.toString();
    }

    //    test
//    public static void main(String[] args) {
//        String ans = newMd5.encrypt("123456");
//        System.out.println(ans);
//    }
}

